/*
 * Copyright 2012 Alibaba.com All right reserved. This software is the
 * confidential and proprietary information of Alibaba.com ("Confidential
 * Information"). You shall not disclose such Confidential Information and shall
 * use it only in accordance with the terms of the license agreement you entered
 * into with Alibaba.com.
 */
package com.jrh.common.json;

import java.io.IOException;

import org.codehaus.jackson.JsonParseException;
import org.codehaus.jackson.JsonParser;
import org.codehaus.jackson.map.DeserializationConfig;
import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.map.ObjectMapper;

/**
 * 类TestJackson.java的实现描述：TODO 类实现描述
 * 
 * @author IBM 2012-4-20 上午10:05:51
 */
public class TestJackson {

    private static ObjectMapper jsonParser; // JSON解析器，考虑到淘宝返回数据中可能存在多种日期格式而做了相应解析配置

    static {
        jsonParser = new ObjectMapper();
        jsonParser.configure(JsonParser.Feature.ALLOW_SINGLE_QUOTES, true); // 淘宝接口混合使用单引号和双引号。
        // jsonParser.configure(JsonParser.Feature.ALLOW_BACKSLASH_ESCAPING_ANY_CHARACTER, true);
        jsonParser.configure(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES, false);
        jsonParser.configure(JsonParser.Feature.ALLOW_UNQUOTED_CONTROL_CHARS, true); // 某些非标准JSON中包含未转义的控制字符，兼容之

    }

    /**
     * @param args
     * @throws IOException
     * @throws JsonMappingException
     * @throws JsonParseException
     */
    public static void main(String[] args) throws JsonParseException, JsonMappingException, IOException {
        testBackslash();
        //testSingleQuotesUnescaped();
        //testSingleQuotesBackslashEscaped();
    }

    public static void testBackslash() throws JsonParseException, JsonMappingException, IOException {
        String test1 = "{\"aa\":\"b\\\"}";
        TestPojo tpR = jsonParser.readValue(test1, TestPojo.class);
        System.out.println(test1 + " " + tpR);

        TestPojo tp = new TestPojo();
        tp.setAa("b\\");
        String t = jsonParser.writeValueAsString(tp);
        System.out.println(t + " " + tp);
    }

    public static void testSingleQuotesUnescaped() {
        try {
            final ObjectMapper om = new ObjectMapper();
            final String jsonUnescaped = "{ \"x\" : \"it's a girl\"}";
            String t = om.readTree(jsonUnescaped).get("x").getTextValue();
            System.out.println(t);
        } catch (final Exception e) {
        }
    }

    public static void testSingleQuotesBackslashEscaped() {
        try {
            final String jsonBackslashEscapedSingleQuote = "{ \"x\" : \"it\\'s a boy\"}";
            String t = jsonParser.readTree(jsonBackslashEscapedSingleQuote).get("x").getTextValue();
            System.out.println(t);
        } catch (final Exception e) {
        }
    }
}
